import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '/models/pack_detail_response.dart';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart'; 
import 'dart:convert';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';
import '../../utils/rangeInput_formatter.dart';

class PackDetailScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;
  const PackDetailScreen({super.key, required this.jsonData});

  @override
  _PackDetailScreenState createState() => _PackDetailScreenState();
}

class _PackDetailScreenState extends State<PackDetailScreen> with WidgetsBindingObserver {
  late double _fontScale;
  // 定义文本样式常量 - 与ReceivingDetailItemScreen保持一致
  late double _baseFontSize = 12.0;
  late double _smallFontSize = 11.0;
  
  String? selectedLpn; // 选中的LPN编号（用于状态判断）
  bool _isLoading = false;
  bool _isReadOnly = false;
  bool _isButtonEnabled = false;
  
  final _barcodeController = TextEditingController();
  final _manualInputFocus = FocusNode();
  final ScrollController _scrollController = ScrollController();

  // 新增：键盘控制核心变量
  bool _inputKeyboardVisible = false; // 输入框键盘显示状态
  bool _isInputFocused = false;       // 输入框焦点状态

  late Map<String, String> orderDetails;
  late PackDetail? responseData;
  late List<ReceivingShipmentLine> _shipmentLines; // 直接使用原始数据列表，替代字符串列表

  int? warehouseId;
  String? remainningQty = '';
  int? shipmentLineId;
  String? internalItemNumber = '';

  // 新添加的状态变量
  String? _selectedReason;
  bool _showReason = false;
  final List<String> _reasonOptions = [
    'Lost', 
    'Damaged', 
    'Incorrect Quantity',
    'Not Arrived',
    'Expired',
    'Wrong Item',
    'Quality Issue',
    'Other'
  ];

  // 计算最大允许输入值
  var helpText = '';
  int maxAllowedValue = 0;

  // 统一样式定义 - 与ReceivingDetailItemScreen保持一致
  TextStyle get _detailLabelStyle {
    return TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: _baseFontSize * _fontScale,
    );
  }

  TextStyle get _detailValueStyle {
    return TextStyle(
      fontSize: _baseFontSize * _fontScale,
    );
  }

  TextStyle get _listTitleStyle {
    return TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: _baseFontSize * _fontScale,
    );
  }

  @override
  void initState() {
    super.initState();
    // 新增：注册应用生命周期监听（后台返回时重置键盘）
    WidgetsBinding.instance.addObserver(this);
    
    _barcodeController.addListener(_updateButtonState);
    _manualInputFocus.addListener(_scrollToBottomWhenFocused);
    // 新增：输入框焦点监听（关联键盘状态）
    _manualInputFocus.addListener(_handleInputFocusChange);
    
    final apiResponse = PackDetailResponse.fromJson(widget.jsonData);
    responseData = apiResponse.data;
    _shipmentLines = responseData?.receivingShipmentLines ?? []; // 初始化原始数据列表
    internalItemNumber = responseData?.itemInfo.internalItemNumber;
    
    // 构建订单详情（逻辑不变）
    orderDetails = {
      'Order': responseData?.orderInfo.orderNumber ?? 'N/A',
      'Order Type': responseData?.orderInfo.orderType ?? 'N/A',
      'Shipment Number': responseData?.shipmentCode ?? 'N/A',
      'Item Number': responseData?.itemInfo.itemNumber ?? 'N/A',
      'Description': responseData?.itemInfo.shortDescription ?? 'N/A',
    };

    // 新增：页面渲染后初始化键盘状态（避免初始异常）
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _resetAllKeyboards();
      }
    });
  }

  // 新增：应用后台返回前台时重置键盘状态
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 新增：输入框焦点变化处理（聚焦弹键盘，失焦收键盘）
  void _handleInputFocusChange() {
    setState(() {
      _isInputFocused = _manualInputFocus.hasFocus;
    });

    if (_isInputFocused && !_inputKeyboardVisible) {
      // 聚焦时：显示键盘 + 同步控件状态
      _showKeyboard();
      setState(() => _inputKeyboardVisible = true);
    } else if (!_isInputFocused && _inputKeyboardVisible) {
      // 失焦时：隐藏键盘 + 同步控件状态
      _hideKeyboard();
      setState(() => _inputKeyboardVisible = false);
    }
  }

  // 新增：键盘显示/隐藏基础方法
  void _showKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
      print('输入框键盘已显示');
    } catch (e) {
      print('显示键盘失败: $e');
    }
  }

  void _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      print('输入框键盘已隐藏');
    } catch (e) {
      print('隐藏键盘失败: $e');
    }
  }

  // 新增：切换输入框键盘状态（点击控件时调用）
  void _toggleInputKeyboard() {
    setState(() {
      _inputKeyboardVisible = !_inputKeyboardVisible;
    });

    if (_inputKeyboardVisible) {
      // 显示键盘：先聚焦输入框，再弹键盘（触发滚动监听）
      _manualInputFocus.requestFocus();
      Future.delayed(const Duration(milliseconds: 100), () => _showKeyboard());
    } else {
      // 隐藏键盘：先失焦，再收键盘
      _manualInputFocus.unfocus();
      Future.delayed(const Duration(milliseconds: 100), () => _hideKeyboard());
    }
  }

  // 新增：重置所有键盘状态（点击空白区域/列表项时调用）
  void _resetAllKeyboards() {
    if (_inputKeyboardVisible || _isInputFocused) {
      setState(() {
        _inputKeyboardVisible = false;
        _isInputFocused = false;
      });
      _manualInputFocus.unfocus();
      _hideKeyboard();
    }
  }

  void _scrollToBottomWhenFocused() {
    if (_manualInputFocus.hasFocus) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_scrollController.hasClients) {
          _scrollController.animateTo(
            _scrollController.position.maxScrollExtent,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        }
      });
    }
  }

  void _updateButtonState() {
    final hasText = _barcodeController.text.trim().isNotEmpty;
    
    // 计算是否显示Reason下拉列表（逻辑不变）
    bool newShowReason = false;
    if (hasText && remainningQty != null && remainningQty!.isNotEmpty) {
      try {
        final receivedQty = int.parse(_barcodeController.text);
        final remainingQty = int.parse(remainningQty!);
        newShowReason = receivedQty != remainingQty;
        if (receivedQty > remainingQty) {
          newShowReason = false;
        }
        maxAllowedValue = int.parse(remainningQty!);
        helpText = '0 - $maxAllowedValue';
      } catch (e) {
        newShowReason = false;
      }
    }
    
    // 更新按钮状态和显示原因的状态（逻辑不变）
    if (_isButtonEnabled != hasText || _showReason != newShowReason) {
      setState(() {
        _isButtonEnabled = hasText;
        _showReason = newShowReason;
        
        // 如果不显示原因，则重置选中的原因
        if (!newShowReason) {
          _selectedReason = null;
        }
      });
    }
  }

  // 处理项选择逻辑 - 适配原始数据列表（新增：选择前重置键盘）
  void _handleItemSelection(ReceivingShipmentLine line) {
    // 新增：点击列表项时先重置键盘状态
    _resetAllKeyboards();
    
    setState(() {
      // 如果点击的是已选中的项，则取消选中并清空相关数据
      if (selectedLpn == line.lpnNumber) {
        selectedLpn = null;
        shipmentLineId = null;
        remainningQty = '';
        helpText = '';
        _barcodeController.clear();
      } else {
        // 否则选中该项并填充数据
        selectedLpn = line.lpnNumber;
        shipmentLineId = line.id;
        
        // 提取数量并填充到输入框（逻辑不变）
        remainningQty = line.orderPackQuantity.toString();
        _barcodeController.text = remainningQty.toString();
        
        // 更新最大值限制（逻辑不变）
        maxAllowedValue = int.tryParse(remainningQty ?? '0') ?? 0;
        helpText = '0 - $maxAllowedValue';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    
    // 屏幕尺寸适配：判断是否为小屏幕
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;
    final viewInsets = mediaQuery.viewInsets;
    
    return MediaQuery(
      data: mediaQuery.copyWith(
        textScaler: TextScaler.linear(isSmallScreen ? 0.85 : 1.0),
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Pack Detail', style: TextStyle(fontSize: 18 * _fontScale)),
          automaticallyImplyLeading: true,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back,color: Color.fromARGB(255, 255, 255, 255)),
            onPressed: () {
              // 新增：返回前重置键盘
              _resetAllKeyboards();
              Navigator.pop(context);
            },
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.home, color: Colors.white),
              onPressed: () {
                // 新增：返回首页前重置键盘
                _resetAllKeyboards();
                Navigator.pushNamed(context, '/home');
              },
            ),
          ],
          backgroundColor: const Color(0xFF008363)
        ),
        // 修改：空白区域点击从仅取消焦点改为重置键盘
        body: GestureDetector(
          onTap: () => _resetAllKeyboards(),
          behavior: HitTestBehavior.opaque,
          child: Padding(
            padding: EdgeInsets.all(isSmallScreen ? 16 : 32), // 适配小屏幕内边距
            child: SingleChildScrollView(
              controller: _scrollController,
              padding: EdgeInsets.only(bottom: viewInsets.bottom + 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 订单详情 - 使用统一样式
                  ..._buildOrderDetails(isSmallScreen),
                  SizedBox(height: 10),

                  // 列表标题：改为"Details:"并应用统一样式
                  Text(
                    'Details:',
                    style: _listTitleStyle,
                  ),
                  
                  SizedBox(height: 4),
                  Container(
                    height: 200,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1.0),
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                    // 双重裁剪确保背景不溢出（逻辑不变）
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4.0),
                      child: ClipRect(
                        child: _shipmentLines.isEmpty
                            ? const Center(child: Text('No details available'))
                            : ListView.builder(
                                physics: const ClampingScrollPhysics(),
                                itemCount: _shipmentLines.length,
                                itemBuilder: (context, index) {
                                  final line = _shipmentLines[index];
                                  final isSelected = selectedLpn == line.lpnNumber;
                                  
                                  // 处理Case类型的Case Qty（逻辑不变）
                                  String? caseQty;
                                  if (line.packType == 'Case' && line.packKey.isNotEmpty) {
                                    caseQty = line.packKey.split('--').last.trim();
                                  }

                                  // 列表项样式：与ReceivingDetailItemScreen保持一致（上下两部分）
                                  return InkWell(
                                    onTap: () => _handleItemSelection(line),
                                    child: Container(
                                      margin: const EdgeInsets.symmetric(vertical: 2),
                                      decoration: BoxDecoration(
                                        border: Border.all(
                                          color: const Color.fromARGB(255, 169, 168, 168), 
                                          width: 0.5
                                        ),
                                        borderRadius: BorderRadius.circular(4.0),
                                        color: isSelected ? Colors.green[50] : null,
                                      ),
                                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          // 上部分：LPN Number（左，加粗） + Desc:值（右，标签不加粗）
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              // 左侧：LPN Number（加粗）
                                              Text(
                                                line.shortDescription,
                                                style: TextStyle(
                                                  fontSize: _smallFontSize * _fontScale,
                                                  fontWeight: FontWeight.bold,
                                                  color: isSelected ? Colors.green : Colors.black,
                                                ),
                                              ),
                                              // 右侧：Desc:值（标签不加粗，值加粗）
                                              Expanded(
                                                child: Padding(
                                                  padding: const EdgeInsets.only(left: 12),
                                                  child: Row(
                                                    mainAxisAlignment: MainAxisAlignment.end,
                                                    children: [
                                                      Text(
                                                        'LPN Number: ',
                                                        style: TextStyle(
                                                          fontSize: _smallFontSize * _fontScale,
                                                          color: isSelected ? Colors.green : Colors.black87,
                                                        ),
                                                      ),
                                                      Text(
                                                        line.lpnNumber ?? 'N/A',
                                                        style: TextStyle(
                                                          fontSize: _smallFontSize * _fontScale,
                                                          fontWeight: FontWeight.bold,
                                                          color: isSelected ? Colors.green : Colors.black87,
                                                        ),
                                                        overflow: TextOverflow.ellipsis,
                                                        maxLines: 1,
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                          const SizedBox(height: 5), // 上下分区间距
                                          
                                          // 下部分：Qty、Pack Type、Case Qty（按需显示）
                                          Row(
                                            children: [
                                              // 字段1：Qty
                                              Expanded(
                                                flex: 1,
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'Qty: ',
                                                      style: TextStyle(
                                                        fontSize: _smallFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      '${line.orderPackQuantity}',
                                                      style: TextStyle(
                                                        fontSize: _smallFontSize * _fontScale,
                                                        fontWeight: FontWeight.bold,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              
                                              // 字段2：Pack Type
                                              Expanded(
                                                flex: 1,
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'Pack Type: ',
                                                      style: TextStyle(
                                                        fontSize: _smallFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      line.packType,
                                                      style: TextStyle(
                                                        fontSize: _smallFontSize * _fontScale,
                                                        fontWeight: FontWeight.bold,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              
                                              // 字段3：Case Qty（仅Case类型显示）
                                              if (line.packType == 'Case')
                                                Expanded(
                                                  flex: 1,
                                                  child: Row(
                                                    mainAxisSize: MainAxisSize.min,
                                                    children: [
                                                      Text(
                                                        'Case Qty: ',
                                                        style: TextStyle(
                                                          fontSize: _smallFontSize * _fontScale,
                                                          color: isSelected ? Colors.green : Colors.black87,
                                                        ),
                                                      ),
                                                      Text(
                                                        caseQty ?? '0',
                                                        style: TextStyle(
                                                          fontSize: _smallFontSize * _fontScale,
                                                          fontWeight: FontWeight.bold,
                                                          color: isSelected ? Colors.green : Colors.black87,
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              ),
                      ),
                    ),
                  ),
                  
                  SizedBox(height: 8),
                  // Remainning Qty 行 - 使用统一样式
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      SizedBox(
                        width: isSmallScreen ? 120 : 150, // 适配小屏幕宽度
                        child: Text(
                          'Remainning Qty:',
                          style: _detailLabelStyle,
                        ),
                      ),
                      SizedBox(width: 10),
                      Text(
                        remainningQty.toString(),
                        style: _detailValueStyle,
                      ),
                    ],
                  ),
                  
                  SizedBox(height: 5),
                  LayoutBuilder(
                    builder: (context, constraints) {
                      // 当屏幕宽度小于300时使用垂直布局（核心修改：添加键盘控件）
                      if (constraints.maxWidth < 200) {
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Received Qty:',
                              style: _detailLabelStyle,
                            ),
                            SizedBox(height: 5),
                            Row(
                              children: [
                                Expanded(
                                  child: Container(
                                    height: 30,
                                    child: TextField(
                                      focusNode: _manualInputFocus,
                                      keyboardType: TextInputType.number,
                                      inputFormatters: [
                                        FilteringTextInputFormatter.digitsOnly,
                                        RangeInputFormatter(maxAllowedValue)
                                      ],
                                      readOnly: _isReadOnly,
                                      controller: _barcodeController,
                                      autofocus: false, // 禁用自动聚焦
                                      decoration: InputDecoration(
                                        border: const OutlineInputBorder(),
                                        contentPadding: EdgeInsets.symmetric(
                                          horizontal: 12,
                                          vertical: 8
                                        ),
                                        // 新增：键盘控制图标
                                        suffixIcon: IconButton(
                                          icon: Icon(
                                            _inputKeyboardVisible ? Icons.keyboard_hide : Icons.keyboard,
                                            color: const Color(0xFF008363),
                                            size: 18,
                                          ),
                                          onPressed: _toggleInputKeyboard,
                                          splashRadius: 18,
                                          padding: const EdgeInsets.all(4),
                                          constraints: const BoxConstraints.tightFor(width: 32, height: 32),
                                        ),
                                      ),
                                      onChanged: (value) => _updateButtonState(),
                                      onTap: () {
                                        // 点击输入框：选中全部文本（若有内容）
                                        if (_barcodeController.text.isNotEmpty) {
                                          _barcodeController.selection = TextSelection(
                                            baseOffset: 0,
                                            extentOffset: _barcodeController.text.length,
                                          );
                                        }
                                        // 确保聚焦（触发焦点监听）
                                        if (!_manualInputFocus.hasFocus) {
                                          _manualInputFocus.requestFocus();
                                        }
                                      },
                                      style: TextStyle(fontSize: _baseFontSize * _fontScale),
                                    ),
                                  ),
                                ),
                                _buildActionButton(40),
                              ],
                            ),
                          ],
                        );
                      } else {
                        // 大屏幕保持水平布局（核心修改：添加键盘控件）
                        return Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(
                              width: isSmallScreen ? 120 : 150, // 适配小屏幕宽度
                              child: Text(
                                'Received Qty:',
                                style: _detailLabelStyle,
                              ),
                            ),
                            SizedBox(width: 5),
                            Container(
                              width: 90,
                              height: 40,
                              child: TextField(
                                focusNode: _manualInputFocus,
                                keyboardType: TextInputType.number,
                                inputFormatters: [
                                  FilteringTextInputFormatter.digitsOnly,
                                  RangeInputFormatter(maxAllowedValue)
                                ],
                                readOnly: _isReadOnly,
                                controller: _barcodeController,
                                autofocus: false, // 禁用自动聚焦
                                decoration: InputDecoration(
                                  border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
                                  contentPadding: EdgeInsets.symmetric(horizontal: 10),
                                  // 新增：键盘控制图标
                                  suffixIcon: IconButton(
                                    icon: Icon(
                                      _inputKeyboardVisible ? Icons.keyboard_hide : Icons.keyboard,
                                      color: const Color(0xFF008363),
                                      size: 18,
                                    ),
                                    onPressed: _toggleInputKeyboard,
                                    splashRadius: 18,
                                    padding: const EdgeInsets.all(4),
                                    constraints: const BoxConstraints.tightFor(width: 32, height: 32),
                                  ),
                                ),
                                onChanged: (value) => _updateButtonState(),
                                onTap: () {
                                  // 点击输入框：选中全部文本（若有内容）
                                  if (_barcodeController.text.isNotEmpty) {
                                    _barcodeController.selection = TextSelection(
                                      baseOffset: 0,
                                      extentOffset: _barcodeController.text.length,
                                    );
                                  }
                                  // 确保聚焦（触发焦点监听）
                                  if (!_manualInputFocus.hasFocus) {
                                    _manualInputFocus.requestFocus();
                                  }
                                },
                                style: TextStyle(fontSize: _baseFontSize * _fontScale),
                              ),
                            ),
                            _buildActionButton(40),
                          ],
                        );
                      }
                    },
                  ),
                  
                  // 新增的Reason下拉列表（样式适配）
                  if (_showReason) ...[
                    SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: isSmallScreen ? 120 : 150, // 适配小屏幕宽度
                          child: Text(
                            'Reason:',
                            style: _detailLabelStyle,
                          ),
                        ),
                        SizedBox(width: 5),
                        Expanded(
                          child: Container(
                            height: 40,
                            padding: EdgeInsets.symmetric(horizontal: 4),
                            decoration: BoxDecoration(
                              border: Border.all(),
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            child: DropdownButtonHideUnderline(
                              child: DropdownButton<String>(
                                value: _selectedReason,
                                hint: Text(
                                  'Select reason', 
                                  style: TextStyle(
                                    color: Colors.grey[700],
                                    fontSize: _baseFontSize * _fontScale
                                  ),
                                ),
                                icon: Icon(Icons.arrow_drop_down, size: 24),
                                iconSize: 24,
                                elevation: 16,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: _baseFontSize * _fontScale
                                ),
                                onChanged: (String? newValue) {
                                  setState(() {
                                    _selectedReason = newValue;
                                  });
                                },
                                items: _reasonOptions.map<DropdownMenuItem<String>>((String value) {
                                  return DropdownMenuItem<String>(
                                    value: value,
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(horizontal: 12),
                                      child: Text(
                                        value,
                                        style: TextStyle(fontSize: _baseFontSize * _fontScale),
                                      ),
                                    ),
                                  );
                                }).toList(),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 构建操作按钮（新增：点击前重置键盘）
  Widget _buildActionButton(double height) {
    return SizedBox(
      height: height,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          padding: EdgeInsets.zero,
          minimumSize: Size(60, height),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.zero,
          ),
          backgroundColor: _isButtonEnabled 
              ? const Color(0xFF008363) 
              : Colors.grey,
        ),
        onPressed: _isButtonEnabled && !_isLoading
            ? () {
                // 新增：点击GO前重置键盘
                _resetAllKeyboards();
                _handleSubmitted(int.tryParse(_barcodeController.text) ?? 0);
              } 
            : null,
        child: _isLoading 
            ? SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  color: Colors.white,
                ),
              )
            : Text(
                'GO',
                style: TextStyle(
                  fontWeight: FontWeight.bold, 
                  fontSize: 16 * (height / 40) * _fontScale,
                  color: Colors.white
                ),
              ),
      ),
    );
  }

  // 构建订单详情 - 适配统一样式和小屏幕
  List<Widget> _buildOrderDetails(bool isSmallScreen) {
    return orderDetails.entries.map((entry) {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 4), // 缩小垂直间距，更紧凑
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: isSmallScreen ? 120 : 150, // 适配小屏幕宽度
              child: Text(
                '${entry.key}:',
                style: _detailLabelStyle,
              ),
            ),
            SizedBox(width: 5), // 缩小水平间距
            Expanded(
              child: Text(
                entry.value,
                style: _detailValueStyle,
                overflow: TextOverflow.ellipsis, // 长文本截断
                maxLines: 1,
              ),
            ),
          ],
        ),
      );
    }).toList();
  }

  // 提交处理（新增：提交前/后重置键盘）
  void _handleSubmitted(int value) async {
    if (!_isButtonEnabled || _isLoading) return;
    // 已在GO按钮点击时重置键盘，此处仅做安全校验
    _resetAllKeyboards();
    
    // 检查是否需要填写原因但未选择
    if (_showReason && (_selectedReason == null || _selectedReason!.isEmpty)) {
      MessageBox.showMessageBox(context, 'Please select a reason', isError: true);
      return;
    }
    
    setState(() {
      _isLoading = true;
      _isReadOnly = true;
    });
    try {
      bool isMatch = false;
      if (responseData != null && selectedLpn != null) {
        // 修复匹配逻辑（适配原始数据列表）
        isMatch = _shipmentLines.any((line) => line.lpnNumber == selectedLpn);
      }
      
      if (!isMatch) {
        MessageBox.showMessageBox(context, 'No matching shipment line found', isError: true);
        return;
      }

      Map<String, dynamic> details = await _confirmedReceiving(
        shipmentLineId: shipmentLineId,
        receivedQuantity: value,
        reason: _selectedReason,
      );

      if (!mounted) return;
      print('details---$details');

      // 先显示消息弹窗，用户确认后再返回
      await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(
              details['code'] == 2000 ? 'Success' : 'Error',
              style: TextStyle(
                fontSize: 18 * _fontScale, 
                color: details['code'] == 2000 
                    ? const Color.fromARGB(255, 4, 170, 10) 
                    : const Color.fromARGB(255, 255, 17, 0)
              ),
            ),
            content: SingleChildScrollView(
              child: ListBody(
                children: <Widget>[
                  Text(details['code'] == 2000?'Received successfully.':details['msg']),
                ],
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('OK'),
                onPressed: () {
                  Navigator.of(context).pop(); // 关闭弹窗
                },
              ),
            ],
          );
        },
      );
      
      // 弹窗关闭后再返回上一页
      Navigator.of(context).pop(details['code'] == 2000);
    } catch (e) {
      // 错误处理
      setState(() {
        _isLoading = false;
        _isReadOnly = false;
      });
      
      if (mounted) {
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text(
                'Error',
                style: TextStyle(fontSize: 18 * _fontScale, color: const Color.fromARGB(255, 255, 17, 0)),
              ),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text(e.toString()),
                  ],
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: const Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _isReadOnly = false;
        });
        // 新增：提交完成后重置键盘（避免异常状态残留）
        _resetAllKeyboards();
      }
    }
  }

  // 调用API确认收货（逻辑完全不变）
  Future<Map<String, dynamic>> _confirmedReceiving ({
    required int? shipmentLineId,
    required int receivedQuantity,
    String? reason,
  }) async {
    print('进来了---');
    if (responseData == null) {
      throw Exception('Invaild receiving data.');
    }

    final apiUrl = '${ApiService.baseURL}${ApiService.updateReceiving}';
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }
    
    try {
      final requestBody = {
        'shipment':responseData!.id,
        'shipment_line_id': shipmentLineId,
        'status': 'Received',
        'received_quantity': receivedQuantity,
        'internal_item_number':internalItemNumber,
        'reason': reason,
      };
      print('reason---$reason');
      print('apiUrl---$apiUrl');
      print('requestBody---$requestBody');
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if (jsonData['code'] == 401) {
          authService.logout(context);
          throw Exception('The session has expired, Please log in again.');
        } else {
          throw Exception('${jsonData['msg']}');
        }
      } else {
        throw Exception('${response.statusCode} - ${response.body}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  @override
  void dispose() {
    // 新增：移除生命周期监听和焦点监听
    WidgetsBinding.instance.removeObserver(this);
    _manualInputFocus.removeListener(_handleInputFocusChange);
    
    _barcodeController.removeListener(_updateButtonState);
    _barcodeController.dispose();
    _manualInputFocus.removeListener(_scrollToBottomWhenFocused);
    _manualInputFocus.dispose();
    _scrollController.dispose();
    super.dispose();
  }
}